﻿using System;
using Microsoft.Practices.EnterpriseLibrary.Caching;

namespace PJ.Data
{
    public abstract class EntityCache<T> : ObjectDataCache<T>, IEntityCache<T>
        where T : class, IEntityData
    {
        public EntityCache(ICacheManager cache)
            : base(cache)
        {
        }
        /// <summary>
        /// Finds the data object in the cache using Entity id
        /// </summary>
        /// <param name="ID">Entity id</param>
        /// <returns>The data object if found or returns null</returns>
        public T FindById(string id)
        {
            return FindByKey("Id", id);
        }
        /// <summary>
        /// FindByID : Finds the data object in the cache using Entity ID
        /// </summary>
        /// <param name="typeName">Entity type name</param>
        /// <param name="ID">Entity ID</param>
        /// <returns>The data object if found or returns null</returns>
        IEntityData IEntityCache.FindById(string id)
        {
            return this.FindById(id);
        }
        /// <summary>
        /// Adds the <see cref="IObjectData"/> instance to the cache.
        /// </summary>
        /// <param name="instance">Instance to add to the cache</param>
        /// <returns><paramref name="instance"/> value<see langword="null" /></returns>
        /// <exception cref="ArgumentNullException">If the passed <paramref name="instance"/> is <see langword="null" />.</exception>
        /// <exception cref="ArgumentException">If the passed <paramref name="instance"/> GlobalID or one of the child class key properties (Id for <see cref="IEntityData"/>, Name for <see cref="IItemData"/>, etc) are <see langword="null" /> or empty.</exception>
        public override T Add(T instance)
        {
            if (instance == null)
                throw new ArgumentNullException();
            if (string.IsNullOrEmpty(instance.Id))
                throw new ArgumentException();
            base.Add(instance);
            AddKey(instance.GlobalId, "Id", instance.Id);
            return instance;
        }

    }
}
